<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    let arr = [
        {id: 1, name: '部门1', pid: 0},
        {id: 2, name: '部门2', pid: 1},
        {id: 3, name: '部门3', pid: 1},
        {id: 4, name: '部门4', pid: 3},
        {id: 5, name: '部门5', pid: 4},
    ]

    const tree = [
        // {id: 1, name: '部门1', pid: 0}
    ]
    const ids = arr.map(item => item.id)

    for (let i = 0; i < arr.length; i++) {
        // 找出不包含在 ids 里的 pid，代表该条数据没有父级
        if (!ids.includes(arr[i].pid)) {
            tree.push(arr[i])
            arr.splice(i, 1)
            i--
        } else {
            // console.log(arr[i].pid)
            // 首先将剩余的 pid 和 tree 里比较，匹配上就 push，这里是获取2级对象
            const treeIds = tree.map(item => item.id)
            const index = treeIds.findIndex(id => id === arr[i].pid)
            if (index > -1) {
                if (Array.isArray(tree[index].children)) {
                    tree[index].children.push(arr[i])
                    arr.splice(i, 1)
                    i--
                } else {
                    tree[index].children = []
                    tree[index].children.push(arr[i])
                    arr.splice(i, 1)
                    i--
                }
            }
        }
    }
    console.log(tree, arr);

    // console.log(tree, arr)
</script>
</body>
</html>
